package com.sc.data.service;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.sc.data.entity.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author shuchang
 * @Date 2018/3/15 下午2:30
 */
@Slf4j
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    private static final String WEATHER_URL="http://wthrcdn.etouch.cn/weather_mini?";

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_URL+"citykey="+cityId;
        return getData(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_URL+"city="+cityName;
        return getData(uri);
    }



    private WeatherResponse getData(String uri){
        WeatherResponse weatherResponse = null;
        ValueOperations<String, String> opsForValue=stringRedisTemplate.opsForValue();;
        //先从缓存中取
        if(stringRedisTemplate.hasKey(uri)){
            try {
                weatherResponse = objectMapper.readValue(opsForValue.get(uri), WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //缓存没有 抛出异常
            throw new RuntimeException("没有缓存数据");
        }
        return weatherResponse;
    }
}
